from itchat.content import *
from config import conf
from log import logger
import itchat, os, requests, json


# 订阅私聊消息
@itchat.msg_register(TEXT)
def handler_single_msg(msg):
    pass

# 订阅群聊消息
@itchat.msg_register(TEXT, isGroupChat=True)
def handler_group_msg(msg):
    config = conf()
    try:
        res = requests.post(
            url="{}/flybot/v1/message_subscriber".format(config.get("api_url")),
            headers = {'x-api-key': config.get("api_key")},
            json = {
                "source": "group",
                "state": "waiting",
                "message": msg
            },
            timeout = (5, 10)
        )
        if msg["Content"].startswith("/imagine"):
            itchat.send(
                "@{}\n🚀消息已收到，处理中。。。".format(msg['ActualNickName']),
                toUserName=msg['FromUserName']
            )
        print(res.text)
    except:
        # 服务器异常
        print("服务器异常")



class WeixinRobot():
    def __init__(self):
        self.config = conf()

    def start(self):
        try:
            # 设置热启动
            itchat.auto_login(enableCmdQR=2, hotReload=True)
        except:
            # 有异常清理记录后再次热启动
            logger.error("Hot reload failed, try to login without hot reload")
            itchat.logout()
            os.remove("itchat.pkl")
            itchat.auto_login(enableCmdQR=2, hotReload=True)

        try:
            logger.info("Wechat login success, user_id: {}, nickname: {}".format(
                itchat.instance.storageClass.userName,
                itchat.instance.storageClass.nickName
            ))
            # 将机器人注册到管理平台
            requests.post(
                url="{}/flybot/v1/register".format(self.config.get("api_url")),
                headers={'x-api-key': self.config.get("api_key")},
                json={
                    "bot_type": self.config.get("bot_type"),
                    "hostname": self.config.get("hostname"),
                    "username": self.config.get("username"),
                    "password": self.config.get("password"),
                    "bot_path": os.getcwd(),
                    "process_id": str(os.getpid()),
                    "extra": self.config.get("extra")
                },
                timeout=(5, 10)
            )
        except Exception as e:
            logger.error("App startup failed!")
            logger.exception(e)
        else:
            itchat.run()

